<template>
    <div class="form-page">
        <el-form
            v-show="showBaseCourse"
            ref="form"
            :model="form"
            label-width="8em"
            :rules="formRules"
            class="data-form"
        >
            <div class="form-item xy-start al-str">
                <div class="title">广告设置</div>
                <div class="yx-start al-start data">
                    <el-form-item
                        label="行业分类"
                        prop="industryId"
                    >
                        <el-select
                            placeholder="行业分类"
                            clearable
                            v-model="form.industryId"
                            @change="choseExam"
                            @clear="getExamOptions"

                        >
                            <el-option
                                v-for="item in industryOptions"
                                :key="item.name"
                                :label="item.name"
                                :value="item.id"

                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item
                        label="考试"
                        prop="examId"
                    >
                        <el-select
                            v-model="form.examId"
                            placeholder="考试"
                        >
                            <el-option
                                v-for="item in examOptions"
                                :key="item.name"
                                :label="item.name"
                                :value="item.id"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item
                        style="width:50%"
                        label="广告位"
                        prop="positionCode"
                        size="mini"
                    >
                        <el-select v-model="form.positionCode" placeholder="请选择">
                            <el-option
                                v-for="item in positionCodeOps"
                                :key="item.code"
                                :label="item.name"
                                :value="item.code">
                            </el-option>
                        </el-select>
                    </el-form-item>


                    <div v-if="showFlag">
                    <el-form-item
                        style="width:50%"
                        label="标题"
                        prop="title"
                        size="mini"
                    >
                        <el-input v-model="form.title"></el-input>
                    </el-form-item>
                    </div>
                    <div v-if="showFlag">

                    <el-form-item
                        style="width:50%"
                        label="排序"
                        prop="sort"
                        size="mini"
                    >
                        <el-input v-model="form.sort"></el-input>
                    </el-form-item>
                    </div>
                    <el-form-item label="封面" prop="cover">
                        <div style="display: flex;flex-direction: row">
                            <div>
                                <upload-img
                                    v-model="form.cover"
                                    :cover="form.cover"
                                    :size="5*1024*1024"
                                    @courseCoverImg="courseCoverImg"
                                >
                                </upload-img>
                            </div>

                            <div style="margin-left: 50px;margin-top: 40px;">
                                <span style="color: red;">
                                    推荐说明:
                                </span>
                                <span>
                                    支持jpg/gif/png格式,App和小程序轮播图建议尺寸比例为3:1,Pc轮播图建议尺寸402x1920px,5M以内
                                </span>
                            </div>
                        </div>
                    </el-form-item>

                    <el-form-item
                        style="width:50%"
                        label="简介"
                        prop="introduction"
                        size="mini"
                    >
                        <el-input v-model="form.introduction"></el-input>
                    </el-form-item>
                    <el-form-item
                        style="width:50%"
                        label="是否多图"
                        prop="pictureCount"
                        size="mini"
                    >
                        <el-radio-group v-model="form.pictureCount">
                            <el-radio :label="0">无图</el-radio>
                            <el-radio :label="1">单图</el-radio>
                        </el-radio-group>

                    </el-form-item>
                    <el-form-item
                        style="width:50%"
                        label="是否跳转"
                        prop="jumpType"
                        size="mini"
                    >
                        <el-radio-group v-model="form.jumpType">
                            <el-radio :label="0">不跳转</el-radio>
                            <el-radio :label="1">跳转文本</el-radio>
                            <el-radio :label="2">跳转链接</el-radio>
                            <el-radio :label="3">内部跳转</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item
                        style="width:50%"
                        label="跳转地址"
                        prop="jumpUrl"
                        size="mini"
                    >
                        <el-input v-model="form.jumpUrl"></el-input>
                    </el-form-item>
                    <el-form-item
                        style="width:50%"
                        label="客户端"
                        prop="clientType"
                        size="mini"
                    >
                        <el-radio-group v-model="form.clientType">
                            <el-radio :label="0">pc</el-radio>
                            <el-radio :label="1">app</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item v-if="showFlag" label="内容" prop="content">
                        <tinymce v-if="showTinymce" v-model="form.content"/>
                    </el-form-item>
                    <div>
                        <el-button
                            class="next-btn"
                            type="info"
                            :loading="submitFlag"
                            @click="clickCancel('advertisementList')"
                        >
                            取消
                        </el-button>
                        <el-button
                            class="next-btn"
                            type="primary"
                            :loading="submitFlag"
                            @click="saveArticle('form')"
                        >
                            保存
                        </el-button>
                    </div>
                </div>
            </div>
        </el-form>
    </div>
</template>

<script>
import {FormPage} from "@/layout/mixin/iVue.js";

import {fetchArticleColumnChildren, fetchArticleColumnFirst} from "@/api/course.js";
import {get} from "@/api/request";
import Tinymce from "@/components/Tinymce";
import {ossUpload} from "@/utils/file.js";
import UploadImg from "@/views/models/content/materialInfoBase/UploadImg";
import {beanCopy} from "@/utils";

export default {
    name: "advertisementAddSetting",
    components: {
        Tinymce,
        UploadImg
    },
    mixins: [FormPage],

    data() {
        const numberPass = (rule, value, callback) => {
            let reg = /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g;
            if (value === "") {
                callback(new Error("请输入内容"));
            } else if (!reg.test(value)) {
                callback(new Error("请输入数字"));
            } else {
                callback();
            }
        };
        return {
            showFlag: false,
            form: {examId: null, content: null},
            industryOptions: [],
            examOptions: [],
            positionCodeOps: [],
            fileList: [],
            fileInfos: [],
            showLinkFlag: false,
            treeProps: {
                label: "name",
                children: "children"
            },
            groupKey: 0,
            articleColumnProps: {
                lazy: true,
                checkStrictly: true,
                lazyLoad: this.getArticleColumnSta,
                emitPath: false
            },
            textarea: "",

            showTinymce: true,
            value: "",
            active: 0,
            key: 0,
            isAdd: false,
            showCa: false,

            message: "first",
            showHeader: false,
            showBaseCourse: true,
            showCredit: false,
            showCharge: false,
            isDisabled: false,
            formRules: {
                title: [
                    {
                        required: true,
                        message: "请输入标题",
                        trigger: "blur"
                    },
                    {
                        min: 2,
                        max: 100,
                        message: "长度在 2 到 100 个字符",
                        trigger: "blur"
                    }
                ],
 /*               examId: [
                    {
                        required: true,
                        message: "考试必填",
                        trigger: "change"
                    }
                ],

                industryId: [
                    {
                        required: true,
                        message: "行业必填",
                        trigger: "change"
                    }
                ],*/
                positionCode: [
                    {
                        required: true,
                        message: "广告位必填",
                        trigger: "change"
                    }
                ],
                pictureCount: [
                    {
                        required: true,
                        message: "是否多图必填",
                        trigger: "change"
                    }
                ],
                sort: [
                    {
                        required: true,
                        message: "排序必填",
                        trigger: "blur"
                    }
                ],
                jumpType: [
                    {
                        required: true,
                        message: "是否跳转必填",
                        trigger: "change"
                    }
                ], clientType: [
                    {
                        required: true,
                        message: "客户端必填",
                        trigger: "change"
                    }
                ],
                content: [
                    {
                        required: true,
                        message: "请输入内容",
                        trigger: "change"
                    }
                ]
            },
            courseType: 0,
            dialogTableVisible: false,
            categories: null,
            classificationInfo: [],
            classficationQueryData: {
                size: 1000
            }
        };
    },
    watch: {
        "form.content"(newInfo, oldInfo) {
            console.log("newinfo", newInfo)
            if (this.showFlag && (!newInfo || !oldInfo)) {
                this.$refs["form"].validate(res => {
                })
            }
        }
    },
    activated() {
        this.showTinymce = true;
    },
    deactivated() {
        this.showTinymce = false;
    },
    created() {
        this.getPositionCodeOps();
        this.getIndustryOptions();
    },
    methods: {
        choseExam() {
            get("/exam/exam/list", {"industryId": this.form.industryId, "size": 1000}).then(res => {
                this.examOptions = res;
                this.form.examId = null
            });
        },

        getIndustryOptions() {
            get("/exam/industry/list",{size: 1000}).then(res => {
                this.industryOptions = res;
            });
        },
        getExamOptions() {
            get("/exam/exam/list").then(res => {
                console.log("res", res);
                this.examOptions = res;
            });
        },
        getPositionCodeOps() {
            get("/advertisement/position/list").then(res => {
                this.positionCodeOps = res
            })
        },

        handleRemove(file, fileList) {
            this.$confirm(`确定移除 ${file.name}？`, "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(res => {
                    console.log("fileList", fileList);
                    this.fileList = fileList;
                    console.log("this.fileList", this.fileList);
                }
            );
        },
        onchange(file, fileList) {
            let imgReaderl = new FileReader();
            imgReaderl.onload = evt => {
                this.base64Header = evt.target.result;
            };
            imgReaderl.readAsDataURL(file.raw);
            ossUpload("cdn", file.raw.name, file.raw, p => {
                file.percentage = p * 100;
                file.status = "uploading";
            }).then(result => {
                file.path = result;
                file.status = "done";
            });
            console.log("fileList", fileList)
            this.fileList = fileList
            console.log("this.fileList", this.fileList)


        },
        saveArticle(formName) {
            this.$refs[formName].validate(valid => {
                if (!valid) {
                    console.log("error submit!!");
                    return false;
                }
            });
            if (this.addAction) {
                this.clickSave(
                    "/advertisement/update",
                    this.form,
                    false,
                    "advertisementList"
                );
            } else {
                this.clickSave(
                    "/advertisement/update",
                    this.form,
                    true,
                    "advertisementList"
                );
            }
        },

        showLink() {
            console.log("this.form.type", this.form.type);
            if (this.form.type === "链接") {
                console.log("show");
                this.showLinkFlag = true;
            } else {
                console.log("close");
                this.showLinkFlag = false;
                this.form.url = null;
            }
        },
        getArticleColumnSta(node, resolve) {
            const {level} = node;
            if (!node.data) {
                fetchArticleColumnFirst({
                    articleCategoryId: this.articleCategoryId
                }).then(res => {
                    const nodes = Array.from(res).map(item => {
                        return {
                            value: item.id,
                            label: `${item.name}`,
                            leaf: level >= (item.children.length > 0 ? 1 : 0)
                        };
                    });
                    resolve(nodes);
                });
            } else {
                fetchArticleColumnChildren({id: node.data.value}).then(
                    res => {
                        const nodes = Array.from(res).map(item => {
                            return {
                                value: item.id,
                                label: `${item.name}`,
                                leaf:
                                    level >=
                                    (item.children.length > 0 ? level + 1 : 0)
                            };
                        });
                        resolve(nodes);
                    }
                );
            }
        },

        async loadData(id) {
            this.isAdd = id === undefined;
            return Promise.all([this.loadCourseOld(id)]).catch(e => {
                this.$message.error("数据加载失败，请稍后在试");
            });
        },
        async loadCourseOld(id) {
            if (!id) {
                this.showFlag = true
                return;
            }
            get(`/advertisement/detail/${id}`).then(result => {
                // this.courseType = result.courseTypeId;
                // let resultCategories = [];
                // if (result.categories !== null) {
                //   result.categories.map(data => {
                //     resultCategories.push(data.id)
                //   })
                // }
                // // result.courseSubjectId = result.classificationIds;
                // this.categories = resultCategories;

                // if (result.type === "链接") {
                //     this.showLinkFlag = true;
                // }
                // this.queryData.articleColumnId = result.articleColumnId;
                this.isDisabled = true;
                this.form = result;
                get("/exam/exam/list", {"industryId": result.industryId}).then(res => {
                    this.examOptions = res;
                });
                console.log("re", result);
                this.showFlag = true
            });
        },
        //封面
        courseCoverImg(url) {
            this.form.cover = url;
        }
    }
};
</script>

<style lang="css" scoped>
.next-btn {
    margin-left: 12px;
}

.course-table-edit-from .el-textarea {
    width: 60em;
    max-width: 60em;
}

.form-page .form-item .data {
    grid-template-columns: repeat(1, auto);
}
</style>
